import 'package:get/get.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_obj/data_type_model.dart';
import 'package:yt_devops/model/device_obj/output_data_model.dart';
import 'package:yt_devops/model/device_obj/services_model.dart';
import 'package:yt_devops/model/device_obj/spec/array_spec.dart';
import 'package:yt_devops/model/device_obj/spec/struct_spec.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_set_interface.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/toast_utils.dart';

class EnergyManageSetController extends GetxController {
  /// 请求
  DeviceServices deviceServices = Get.find<DeviceServices>();

  /// 下发数据
  Map<String, dynamic> formData = {};

  /// 设备id
  late int deviceId;
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  /// 验证是否所有参数已填
  bool validate(List<ServicesModel> services, Map<String, dynamic> data) {
    List<OutputDataModel> outputData = [];
    outputData = services.fold(outputData,
        (previousValue, element) => previousValue..addAll(element.outputData));
    if (data.isEmpty) {
      TotastUtils.tip(Get.context!, title: '请输入要下发的参数');
      return false;
    }
    for (var output in outputData) {
      var key = output.id;
      var value = data[key];

      if (value is List) {
        for (var item in value) {
          if (item is Map) {
            for (var k in item.keys) {
              if (item[k] == null || item[k] == '' || item[k] == '-') {
                var struct = (output.dataType.specs as ArraySpec).item?.specs
                    as StructSpec;
                var idx =
                    struct.specs!.indexWhere((element) => element.id == k);
                if (idx > -1) {
                  TotastUtils.tip(Get.context!,
                      title: '${ResKey.plsInput.tr}${struct.specs![idx].name}');
                  return false;
                }
              }
            }
          }
        }
      } else if (value is Map) {
        for (var k in value.keys) {
          if (value[k] == null) {
            var struct = output.dataType.specs as StructSpec;
            var idx = struct.specs!.indexWhere((element) => element.id == k);
            if (idx > -1) {
              TotastUtils.tip(Get.context!,
                  title: '${ResKey.plsInput.tr}${struct.specs![idx].name}');
              return false;
            }
          }
        }
      } else {
        if (value == null && output.dataType.type != DataTypeEnum.array) {
          TotastUtils.tip(Get.context!, title: '${ResKey.plsInput.tr}${output.name}');
          return false;
        }
      }
    }
    return true;
  }

  void sendCommand(
          String deviceId,
          String serviceId,
          Map<String, dynamic> data,

          ///确认回调
          Function(bool success, {Map<String, dynamic>? data})?
              confirmHandler) =>
      Configs.httpClient.requestWithLoading(
        () async {
          Map<String, dynamic> params = {
            'deviceId': deviceId,
            'serviceId': serviceId,
            'input': data
          };
          await deviceServices.deviceRemoteSetting(params);
          FuncUtils.requestTipsDislog(
              Get.context!, ResKey.executeSuccess.tr, true);
          update();
          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () {
              Get.back();
              confirmHandler?.call(true, data: data);
            },
          );
        },
        onError: (err) {
          FuncUtils.requestTipsDislog(
              Get.context!, ResKey.executeFailure.tr, false);

          Future.delayed(
            const Duration(
              milliseconds: 1000,
            ),
            () => Get.back(),
          );
          confirmHandler?.call(false);
          return true;
        },
      );
}
